const {comMysql} = require("../db/mysql")


const addBlog=(req,res)=>{  
  
  let {content,way,img,title,editContent,username,realname} = req.body
  let time = new Date().getTime()
  console.log(username)
  !username&&(username = null)
  !realname&&(realname = null)
  let sql =  `insert into blogs(title,content,editContent,goodNum,collectNum,seeNum,way,time,username,realname) values (?,?,?,?,?,?,?,?,?,?)`
  let arr=[title,content,editContent,0,0,0,way,time,username,realname]
  
  
  return comMysql(sql,arr)
  
}

const delBlog=(req,res)=>{
  let {id} = req.body
  let sql = `delete from blogs where id = ?`
  let arr = [id]
  return comMysql(sql,arr)
}

const updateBlog=(req,res)=>{
  let {id,content,editContent,title,way} = req.body
  console.log(id);
  
  let sql = `update blogs set content = ?,editContent = ?,title = ?,way = ? where id = ?`
  let arr = [content,editContent,title,way,id]
  
  return comMysql(sql,arr)
}

const updateSeeNum = (req,res)=>{
  let {id,seeNum} = req.body
  console.log(seeNum);
  
  let sql = `update blogs set seeNum = ? where id = ?`
  let arr = [seeNum,id]
  
  return comMysql(sql,arr)
}

const updateGoodNum = (req,res)=>{
  let {id,goodNum} = req.body
  let sql = `update blogs set goodNum = ? where id = ?`
  let arr = [goodNum,id]
  return comMysql(sql,arr)
}

const searchBlogInfo = (req,res)=>{
    let sql = `select blogs.title,blogs.goodNum,blogs.username,blogs.realname,blogs.seeNum,count(comment.id) as commentLength from blogs LEFT JOIN comment on blogs.id = comment.blogid GROUP BY blogs.id order by blogs.time desc`
    return comMysql(sql)
}

const searchAllBlog=(req,res)=>{
  let {way,title,id,pagesize,pageno} = req.query
  
  let sql = `select title,content,seeNum,time,goodNum,collectNum,way,id,username,realname from blogs where 1=1 `
  if(way){
    sql+=`and way = "${way}" `
  }
  if(title){
    sql+=`and title like "%${title}%" `
  }
  sql=sql+`order by time desc`

  if(pagesize&&pageno){
    sql+=` limit `+(pageno-1)*pagesize+`,`+pageno*pagesize
  }   
    return comMysql(sql)   
}

const searchBlog=(req,res)=>{
  let {way,title,id,pagesize,pageno} = req.query
  
  let sql = `select * from blogs where 1=1 `
  if(way){
    sql+=`and way = "${way}" `
  }
  if(title){
    sql+=`and title like "%${title}%" `
  }
  if(id){
    sql+=`and id = ${id} `
  }
  sql=sql+`order by time desc`

  if(pagesize&&pageno){
    sql+=` limit `+(pageno-1)*pagesize+`,`+pageno*pagesize
  }   
  return comMysql(sql)
}


module.exports={
  addBlog,
  delBlog,
  updateBlog,
  searchBlog,
  updateSeeNum,
  updateGoodNum,
  searchBlogInfo,
  searchAllBlog
}